$(function() {
    buttenControl();
    initDataTable();
    initOrgSelects();
    //开始时间
    $('#startTime').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: 1,
        todayBtn: 1,
        initialDate:new Date(),
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition:'bottom-right',
    }).on("changeDate",function(e){
        if(e.date != null&&e.date != ''){
            var startTime = Dateinit.getNextDay(e.date); //2018-03-10 14:47
        }
        //前一天与后一天时间的比较清空
        var start2 = new Date(Date.parse($('#startTime').val().replace(/-/g,"/"))); // 中国标准时间
        if(Date.parse(startTime.replace(/-/g,"/"))> start2){
            $("#endTime").val('');
        }
        //设置结束时间的起始值未开始时间的下一天
        $("#endTime").datetimepicker("setStartDate",startTime);
    });
    //结束时间
    $('#endTime').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: 1,
        todayBtn: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition:'bottom-right',
    });
    /*对时间的操作结束*/

    // 新增
    $("#btnAdd").on("click",function () {
        showStationInfo('add');
    });

    // 修改
    $("#btnRevise").click(function(){
        showStationInfo('update');
    });

    // 删除
    $("#btnDelete").click(function () {
        var ids = getSelectedDeleteParams();
        if (ids != '' && ids != null) {
            layerAlert.confirmMessage("确定删除该条？",projectPath + "/base/stations/del?id="+ids, function(data){
                layerAlert.successMessage("删除成功！","");
                $('#tb_ads').bootstrapTable('refresh');
                // if(){}else{}
            });
        }else{
            layerAlert.errorMessage("您的选择为空");
        };
    });
    //经度数字控制
    $("#lat").change(function () {
        debugger;
        if ($("#lat").val() < 73.66 || $("#lat").val() > 135.05) {
            layerAlert.warnMessage("超出国内范围,请重新填写");
            $("#lat").val("");
        }else{
            $(this).val(mustFiveDecimal($(this).val()));
        };
    });
    //纬度数字控制
    $("#lng").change(function () {
        if ($("#lng").val() < 3.86 || $("#lng").val() > 53.55) {
            layerAlert.warnMessage("超出国内范围,请重新填写");
            $("#lng").val("");
        }else{
            $(this).val(mustFiveDecimal($(this).val()));
        };
    });

    // 充电站服务电话验证判断
    $("#serverPhone").on("change",function(){
        var reg = /^(0\d{2,3}-?)?\d{7,8}$/;
        if(!reg.test($(this).val())){
           layerAlert.warnMessage("填写有误");
           $(this).val("");
        };
    });
    // 导出
    $("#btnExport").on("click",function(){
        layer.open({
            type: 1,
            title: "选择导出页数",
            shadeClose: true,
            shade: 0.3,
            move :false,
            area: ['300px', '250px'],
            skin: 'layui-layer-rims',
            content: $(".export_dialog"),
            btn:['确定'],
            closeBtn:1,
            success:function(){
                $('.export_dialog').empty();
                //var endPage=pageCount;
                //var startPage=1;
                var str=[
                    '<div class="form-group" style="margin-top:30px;margin-left: 10px;">',
                    '<label class="label-width3">起始页:</label><input type="text"  class="form-control" id="start_page" value="1" />',
                    '</div>',
                    '<div class="form-group" style="margin-top: 10px;margin-left: 10px;">',
                    '<label class="label-width3">结束页:</label><input type="text"  class="form-control" id="end_page" value="1000"/>',
                    '</div>',
                ].join('');
                $('.export_dialog').append(str);
            },
            close:function(){
                $('.export_dialog').remove(str);
            },
            btn1:function(){
                alert("导出成功");
            }
        });
    });
    // 清空
    $("#btnEmpty").click(function(){
        $("#stationName").val(""); // 充电站名
        $("#stationNo").val(""); // 站编码
        $("#stationAddress").val(""); // 站位置
        $("#stationStatus").val(""); // 站状态
        $("#startTime").val(""); // 开始时间
        $("#endTime").val(""); // 结束时间
        $("#provinceCityPart").val(""); // 省-市-部门
        $("#provinceCityPart").attr("data-id","");
        $("#managerorgName").val(""); // 运维单位
        $("#managerorgName").attr("data-id","");
        $("#prorgcodeName").val(""); // 产权单位
        $("#prorgcodeName").attr("data-id","");
        $("#isThird").val(""); // 是否第三方
    })

    $("#addParkAreaTabsBtn").click(function() {
        if(nthTabs == undefined || nthTabs == null){
            nthTabs = $("#editor-tabs").nthTabs();
        }
        if(nthTabs.getTabList().length >= 4){
            layerAlert.errorMessage("停车区数目最多只能4个");
            return;
        }

        var uuid= "ddd" + Math.ceil(Math.random()*10);
        var addHtmlContent = '<div class="col-md-12">';
        addHtmlContent += '<div class="col-md-12 form-group input-space clearfix">';
        addHtmlContent += '<input type="hidden" name="type" value="add"><input type="hidden" name="uuid" value="">';
        addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">名称：</label><input type="text" class="form-control" name="parkareaname" value=""/></div>';
        addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">编号：</label><input type="text" class="form-control" name="parkareacode" value=""></div>';
        addHtmlContent += '</div>';
        addHtmlContent += '<div class="col-md-12 form-group input-space clearfix">';
        addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">开放时间：</label><input type="text" class="form-control" name="parkareaopenat" value="00:00"></div>';
        addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">结束时间：</label><input type="text" class="form-control" name="parkareacloseat" value="23:59"></div>';
        addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">是否默认：</label><input type="radio" name="defaultshow"></div>';
        addHtmlContent += '</div>';
        addHtmlContent += '<div class="col-md-12 form-group input-space clearfix">';
        addHtmlContent += '<div class="col-md-6 col-sm-6 col-xs-6"><label class="label-width1" style="vertical-align: top;margin-top: 5px;">收费标准：</label> <textarea class="form-control" name="parkingfee" style="height: 100px;"></textarea> </div>';
        addHtmlContent += '<div class="col-md-6 col-sm-6 col-xs-6"><label class="label-width1" style="vertical-align: top;margin-top: 5px;">相关描述：</label> <textarea class="form-control" name="parkingdesc" style="height: 100px;"></textarea></div>';
        addHtmlContent += '</div>';
        addHtmlContent += '</div>';
        nthTabs.addTab({
            id:uuid,
            title:'停车区新增',
            content:addHtmlContent
        });
        nthTabs.setActTab(uuid);
    });

    $("#stationTrace").click(function () {
        layer.open({
            type:1,
            title:"充电站操作轨迹",
            shade:0.3,
            shadeClose: true,
            move :false,
            area: ['80%', '80%'],
            skin: 'layui-layer-rims',
            content:$("#traceDetail"),
            btn:['关闭'],
            fixed:false,
            resize:true,
            // maxmin:true,
            success:function(){
                $.ajax({
                    url:projectPath+'/base/asset/operation/trajectorys/list',
                    type:'post',
                    data:{bussinessTypeEnum:"STATION",assetuuid:$("#uuid").val()},
                    dataType:"json",
                    success:function(data){
                        var track = data.data;
                        var str='';
                        for(var i=0;i<track.length;i++){
                            str+='<div class="vertical-timeline-block">';
                            if(i%3==0){
                                str+='<div class="vertical-timeline-icon yellow-bg">';
                            } else if(i%3==1){
                                str+='<div class="vertical-timeline-icon lazur-bg">';
                            } else {
                                str+='<div class="vertical-timeline-icon blue-bg">';
                            }
                            str+='<i class="fa fa-file-text"></i>';
                            str+='</div>';
                            str+='<div class="vertical-timeline-content">';
                            str+='   <h2>'+track[i].actiontype+'</h2>';
                            var opsource = '';
                            if(track[i].sourcetype == 1){
                                opsource = 'WEB页面';
                                str+='   <p>操作人：'+track[i].sourceuuid+'</p>';
                            } else if(track[i].sourcetype == 2){
                                opsource = '工单';
                                str+='   <p>操作人：'+track[i].sourceuuid+'</p>';
                            } else if(track[i].sourcetype == 3){
                                opsource = 'MQ';
                            } else if(track[i].sourcetype == 4){
                                opsource = '定时任务';
                            } else {
                                opsource = '其他';
                            }
                            str+='   <p>操作来源：'+opsource+'</p>';
                            str+='   <a href="#" class="btn btn-sm btn-primary"> 更多信息</a>';
                            str+='   <span class="vertical-date">';
                            str+='       <small>'+getLocalTime(track[i].operatordate)+'</small>';
                            str+='   </span>';
                            str+='</div>';
                            str+='</div>';
                        }
                        if(str==''){
                            str +='暂无操作记录';
                        }
                        $("#station-timeline").html(str);
                    },
                    error:function(data){
                        layerAlert.errorMessage("不好意思，数据出错啦！");
                    }
                })

            }
        })
    });

    $('#layoutChange').click(function (event) {
        event.preventDefault();
        $('#station-timeline').toggleClass('center-orientation');
    });

    $("#stakeDetail").on("click",function(){
        var index = layer.open({
            type:1,
            title:"充电桩详情",
            shade:0.3,
            shadeClose: true,
            move :false,
            area: ['80%', '60%'],
            skin: 'layui-layer-rims',
            content:$("#stakeDetailDiv"),
            btn:['关闭'],
            fixed:false,
            resize:true,
            // maxmin:true,
            success:function(){
                if($("#uuid").val()!=''){
                    $('#stake_detail').bootstrapTable('refresh', {url: projectPath+"/base/stakes/listByStation"});
                } else {

                }
            },
            btn1:function(){
                layer.close(index);
            }

        });
    })

    /**
     * 验证站名称是否存在 zhangYiHang
     */
    $("#name").change(function () {
        $.ajax({
            url: projectPath + '/base/stations/qryStationCountByName',
            data:{name:$("#name").val()},
            type:'POST',
            dataType:'JSON',
            success:function (r) {
                if(r.data > 0){
                    layerAlert.successMessage2("站名称已存在,如果继续添加则覆盖掉原有数据");
                }
            },
            error:function () {
                layerAlert.errorMessage("网络异常!");
            }
        })
    });

});


function initDataTable(){
    $('#tb_ads').bootstrapTable({
        method: 'POST',                      //请求方式（*）
        //url: 'list.json',         //请求后台的URL（*）
        url: projectPath+"/base/stations/list",
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: true,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:false,
        queryParams: dataQueryParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [3,10,20],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        showRefresh: true,                  //显示刷新按钮
        showToggle: true,
        showColumns: true,                  //是否显示所有的列
        minimumCountColumns: 2,             //最少允许的列数
        singleSelect:true,
        // height:500,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {field: 'check', checkbox: true},
            {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                var pageSize=$('#tb_ads').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber=$('#tb_ads').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: 'stationname', title: '充电站名称',  align: 'center',formatter: function (value, row, index) {
                return '<div style="white-space: nowrap;"><a href="javascript:;" onclick="showStationInfo(\'detail\',\''+row.uuid+'\')">' + value + '</a></div>';
            }},
            {field: 'stationno', title: '站编码',align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'isthird', title: '是否第三方',align: 'center',formatter: function (value, row, index) {
                if(value == "0" || value == "1"){
                    return "<div style='white-space: nowrap;'>否</div>";
                }else{
                    return "<div style='white-space: nowrap;'>是</div>";
                };
            }},
            {field: 'lat', title: '经纬度', align: 'center',formatter: function (value, row, index) {
                return (row.lat+"/"+row.lng);
            }},
            {field: 'stationtype', title: '站类型', align: 'center',formatter:function(value, row, index){
                if(row.isthird == 0 || row.isthird == 1){
                    switch(value){
                        //1高速,2城市公共,3单位内部,4公交,5其他,6出租车，99岸电
                        case 1:
                            value = "高速"
                            break;
                        case 2:
                            value ="城市公共"
                            break;
                        case 3:
                            value ="单位内部"
                            break;
                        case 4:
                            value ="公交"
                            break;
                        case 5:
                            value ="其他"
                            break;
                        case 6:
                            value ="出租车"
                            break;
                        case 99:
                            value ="岸电"
                            break;
                        default:value ="其他"
                    }
                } else {
                    switch(value){
                        //(1公共,50个人,100公交专用,101环卫专用,102物流专用,103出租车专用,255其他,99岸电)；
                        case 1:
                            value ="公共"
                            break;
                        case 50:
                            value ="个人"
                            break;
                        case 100:
                            value ="公交专用"
                            break;
                        case 101:
                            value ="环卫专用"
                            break;
                        case 102:
                            value ="物流"
                            break;
                        case 103:
                            value ="出租车"
                            break;
                        case 99:
                            value ="岸电"
                            break;
                        default:value ="其他"
                    }
                }
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'stationstatus', title: '站状态',  align: 'center',formatter: function (value, row, index) {
                if(value == "2"){
                    return "<div style='white-space: nowrap;'>待投运</div>";
                }else if(value == "3"){
                    return "<div style='white-space: nowrap;'>运行</div>";
                }else if(value == "8"){
                    return "<div style='white-space: nowrap;'>维护</div>";
                }else if(value == "10"){
                    return "<div style='white-space: nowrap;'>停运</div>";
                }else if(value == "11"){
                    return "<div style='white-space: nowrap;'>退运</div>";
                }else{
                    return "";
                }
            }},
            {field: 'servicecode', title: '内外部', align: 'center',formatter: function (value, row, index) {
                if(row.urposetype==2){
                    if(value==1){
                        return "<div style='white-space: nowrap;'>公用-对外开放</div>";
                    } else {
                        return "<div style='white-space: nowrap;'>公用-对内开放</div>";
                    }
                } else {
                    return "<div style='white-space: nowrap;'>专用-不展示</div>";
                }
            }},
            {field: 'provinceName', title: '省份',  align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'cityName', title: '城市', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'provinceOrgName', title: '省组织机构', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'cityOrgName', title: '市组织机构', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'prOrgName', title: '产权单位',align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'managerOrgName', title: '运维单位',align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'rundate', title: '投运时间', align: 'center',formatter: function (value, row, index) {
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'createdat', title: '最近更新时间',align: 'center',formatter: function (value, row, index) {
                if(row.updatedat != '' && row.updatedat != null){
                    value = row.updatedat;
                }
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                }
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }}
        ],
        responseHandler: function (obj) {
            return {
                total:obj.data.total,
                rows:obj.data.data
            }
        }
    });
    $('#tb_ads').bootstrapTable('hideColumn', 'cityName');
    $('#tb_ads').bootstrapTable('hideColumn', 'provinceName');

    $("#btnQuery").click(function(){
        $('#tb_ads').bootstrapTable('refresh', {url: projectPath+"/base/stations/list",pageNumber:1});
    });


    $('#stake_detail').bootstrapTable({
        method: 'POST',                      //请求方式（*）
        url: '',         //请求后台的URL（*）
        contentType: 'application/x-www-form-urlencoded',
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:true,
        queryParams: stakeQueryParams,//传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 15,20],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        showColumns: true,                  //是否显示所有的列
        minimumCountColumns: 2,             //最少允许的列数
        singleSelect:true,
        // height:500,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {
                field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                return index + 1;
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: 'stakeno', title: '桩编号',  align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'stakename', title: '桩名称',  align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'staketype', title: '桩类型', align: 'center',formatter: function (value, row, index) {
                if(value == "1"){
                    value = "专用";
                }else if(value == "2") {
                    value = "公用";
                }else{
                    value = "其他";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'stakestatus', title: '桩状态',  align: 'center',formatter: function (value, row, index) {
                if(value == "2"){
                    value = "待运行";
                }else if(value == "3"){
                    value = "运行";
                }else if(value == "8"){
                    value = "维护";
                }else if(value == "11"){
                    value = "退运";
                }else if(value == "10"){
                    value = "停运";
                }else{
                    value = "其他";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'type', title: '交直流', align: 'center',formatter: function (value, row, index) {
                if(value == "1"){
                    value = "直流充电桩";
                }else if(value == "2"){
                    value = "交流充电桩";
                }else{
                    value = "通用充电桩";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }}
        ],
        responseHandler: function (data) {
            return data.data;
        }
    });

    $('#tab_parking_space').bootstrapTable({
        method: 'GET',                      //请求方式（*）
        //url: '',         //请求后台的URL（*）
        contentType: 'application/x-www-form-urlencoded',
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:true,
        queryParams: queryParkingParams,//传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 5,                       //每页的记录行数（*）
        pageList: [3, 10, 15],        //可供选择的每页的行数（*）
        strictSearch: false,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        showColumns: true,                  //是否显示所有的列
        minimumCountColumns: 2,             //最少允许的列数
        singleSelect:true,
        // height:500,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {
                field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                return index + 1;
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: 'name', title: '停车位名称',  align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'parkno', title: '停车位编码',  align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }}
        ],
        responseHandler: function (data) {
            return data.data;
        }
    });
}

// 表格列表要传的参数
function dataQueryParams() {
    // var filterinfo = new Object();
    var filterinfo = {};
    if ($('#stationName').val() != '') {// 充电站名
        filterinfo.name = $("#stationName").val();
    };
    if ($('#stationNo').val() != '') {// 站编码
        filterinfo.stationno = $("#stationNo").val();
    };
    if ($('#stationAddress').val() != '') {// 站位置
        filterinfo.address = $("#stationAddress").val();
    };
    if ($('#stationStatus').val() != '') {// 站状态
        filterinfo.stationstatus = $("#stationStatus").val();
    };
    if ($('#startTime').val() != '') {//投运开始时间
        filterinfo.rundate_begin = $("#startTime").val();
    };
    if ($('#endTime').val() != '') {// 投运结束时间
        filterinfo.rundate_end = $("#endTime").val();
    };
    if ($('#provinceCityPart').attr("data-id") != '') {// 省-市-部门
        filterinfo.orgCode = $("#provinceCityPart").attr("data-id");
    };
    if($("#managerorgName").attr("data-id") != ''){//运维单位
        filterinfo.managerorgCode = $("#managerorgName").attr("data-id");
    };
    if($("#prorgcodeName").attr("data-id") != ''){//产权单位
        filterinfo.prorgCode = $("#prorgcodeName").attr("data-id");
    };
    if ($('#isThird').val() == '0') {// 是否第三方
        filterinfo.isthrids = '0,1';
    }else if($('#isThird').val() == '1'){
        filterinfo.isthrids = '2,3,4';
    }else{
        filterinfo.isthrids = "";
    };
    filterinfo.offset = (this.pageNumber-1)*this.pageSize;
    filterinfo.limit = this.pageSize;
    return filterinfo;
};

function initOrgSelects(){
    //省市部门弹窗选择
    $("#provinceClick").on("click",function () {
        initOrgTreeLayer("1","选择省市组织","provinceCityPart");
    });

    // 运维单位弹窗选择
    $("#managerorgClick").on("click",function () {
        initOrgTreeLayer("0","选择运维单位","managerorgName");
    });

    // 产权单位弹窗选择
    $("#prorgcodeClick").on("click",function () {
        initOrgTreeLayer("0","选择产权单位","prorgcodeName");
    })

    $("#orgCode").on("click",function () {
        initOrgTreeLayer("1","选择省市组织","orgCode");
    })

    $("#managerorgCode").on("click",function () {
        initOrgTreeLayer("0","选择运维单位","managerorgCode");
    })

    $("#prorgCode").on("click",function () {
        initOrgTreeLayer("0","选择产权单位","prorgCode",2);
    })

    $("#cityCompany").on("click",function () {
        initDistrictTreeLayer("选择行政区划",'cityCompany','jsZtreelayer','search_input');
    })
}

//根据类型展示站详情面板
function showStationInfo(tag,stationuuid){
    var btn=['提交','关闭'];
    var title="";
    getSelectOptionsWithCode({code:'30008002',selectid:'gsname'});
    getSelectOptionsWithCode({code:'30029300',selectid:'standard'});
    listOperatorSelect({selectid:'operatorUuid'});

    if(tag=='add'){
        $("#stakeDetailAndstationTrace").css("display","none");
        $("#editor-tabs").html('');
        nthTabs = null;
        $("#addParkAreaTabsBtn").css("display","block");
        $("#stationForm")[0].reset();
        title = "充电站新增";
        var index = layer.open({
            type:1,
            title:title,
            shade:0.3,
            shadeClose: true,
            move :false,
            area: ['100%', '90%'],
            skin: 'layui-layer-rims',
            content:$("#stationDetailDiv"),
            btn:btn,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
            },
            cancel:function(){
            },
            yes:function(){
                var bootstrapValidator = validatorStation();
                bootstrapValidator.validate();
                //停车区验证
                if(nthTabs == null){
                    layerAlert.warnMessage("请添加停车区");
                    return;
                }
                if(!bootstrapValidator.isValid()){
                    return false;
                }
                //站点类型为高速,高速编码必填
                if($("#stationType").val() == '0-1'){
                    if($("#gsname").val() == '' || $("#gsname").val() == null){
                        layerAlert.warnMessage("站点类型为高速,高速编码必填!");
                        return;
                    };
                }
                saveStation();
                layer.close(index);
            },
            btn2:function(){
                layer.close(index);
            }
        });
    } else if(tag=='update') {
        $("#stakeDetailAndstationTrace").css("display","block");
        var ids = getSelectedDeleteParams();
        if (!ids || ids=='') {
            layerAlert.errorMessage("请选择数据");
            return;
        }
        $("#addParkAreaTabsBtn").css("display","block");
        nthTabs = $("#editor-tabs").nthTabs({allowClose:true});
        getStationInfo(ids);
        title = "充电站修改";
        var index = layer.open({
            type:1,
            title:title,
            shade:0.3,
            shadeClose: true,
            move :false,
            area: ['100%', '90%'],
            skin: 'layui-layer-rims',
            content:$("#stationDetailDiv"),
            btn:btn,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
            },
            cancel:function(){
            },
            yes:function(){
                var bootstrapValidator = validatorStation();
                bootstrapValidator.validate();
                if(!bootstrapValidator.isValid()){
                    return false;
                }
                //站点类型为高速,高速编码必填
                if($("#stationType").val() == '0-1'){
                    if($("#gsname").val() == '' || $("#gsname").val() == null){
                        layerAlert.warnMessage("站点类型为高速,高速编码必填!");
                        return;
                    };
                }
                saveStation();
                layer.close(index);
            },
            btn2:function(){
                layer.close(index);
            }
        });
    } else if (tag=='detail'){
        $("#stakeDetailAndstationTrace").css("display","block");
        $("#addParkAreaTabsBtn").css("display","none");
        getStationInfo(stationuuid);
        btn=['关闭'];
        title = "充电站详情";

        var index = layer.open({
            type:1,
            title:title,
            shade:0.3,
            shadeClose: true,
            move :false,
            area: ['100%', '90%'],
            skin: 'layui-layer-rims',
            content:$("#stationDetailDiv"),
            btn:btn,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
            },
            cancel:function(){
            },
            btn1:function(){
                layer.close(index);
            }
        });
    } else {
        return;
    }
}

//停车区tab对象
var nthTabs;
//ajax获取后台站信息
function getStationInfo(id){
    $("#uuid").val(id);
    // 详情站信息回显
    $.ajax({
        url:projectPath+"/base/stations/"+id,
        type:"GET",
        dataType:"json",
        success:function(data){
            console.log(data.data)
            data = data.data;
            $("#name").val(data.stationname);// 充电站名

            $("#orgCode").val(data.partOrgName); // 所在单位
            $("#orgCode").attr('data-pids',data.provinceorgcode+"-"+data.cityorgcode+"-"+data.partorgcode);

            $("#detailAddress").val(data.address); // 详细地址
            $("#lat").val(data.lat); // 经度
            $("#lng").val(data.lng); // 纬度
            $("#altitude").val(data.altitude);

            //3段存放
            $("#cityCompany").val(data.provinceName+"-"+data.cityName+"-"+data.districtName);
            $("#cityCompany").attr("data-id",data.provincecode+"-"+data.citycode+"-"+data.districtcode);

            $("#managerorgCode").val(data.managerOrgName); // 运维单位
            $("#managerorgCode").attr('data-id',data.managerorgcode);; // 运维单位
            $("#prorgCode").val(data.prOrgName); // 运维单位
            $("#prorgCode").attr('data-id',data.prorgcode);; // 运维单位
            $("#serverPhone").val(data.servicephone); // 服务电话
            $("#isThirdInfo").val(data.isthird); // 是否第三方

            $('#operatorUuid').selectpicker('val', data.operatoruuid);//运营商设置选中
            $('#operatorUuid').selectpicker('refresh');
            //$("#operatorUuid").val(data.operatoruuid); //运营商
            $("#stationType").selectpicker('val',((data.isthird==0||data.isthird==1)?"0":"1")+"-"+data.stationtype); // 站点类型
            $('#stationType').selectpicker('refresh');

            $("#useFun").val(data.urposetype +"-"+ data.servicecode);// 公专用
            $("#stationStatusInfo").val(data.stationstatus); // 站状态
            //$("#buildArea").val(data.construction); // 建设场所
            $("#buildArea").selectpicker('val',data.construction); // 站点类型
            $('#buildArea').selectpicker('refresh');

            $("#gsname").selectpicker('val',data.gscode); // 高速
            $('#gsname').selectpicker('refresh');

            $("#standard").selectpicker('val',data.standard.split(",")); // 国标类型
            $('#standard').selectpicker('refresh');

            var tradetypes = data.tradetypes;
            var groupCheckbox=$("input[name='tradeTypes']");
            for(var i=0;i<groupCheckbox.length;i++){
                if(!isInArray(tradetypes,groupCheckbox[i].value)){
                    groupCheckbox[i].checked=false;
                }
            }
            getStationParkAreaList(id);
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}

//ajax获取站下停车位列表
function getStationParkAreaList(id){
    $.ajax({
        url:projectPath+"/base/stations/qryParkingAreaListForStation?uuid="+id,
        type:"POST",
        dataType:"json",
        success:function(data){
            var arrdate = data.data;
            if(arrdate == "" || arrdate == null || arrdate.length ==0){

            }else{
                nthTabs = $("#editor-tabs").nthTabs({allowClose:true});
                var dataHtml = '';
                for(var i = 0, length1 = arrdate.length; i < length1; i++){
                    dataHtml = '<div class="col-md-12">';
                    dataHtml += '<div class="col-md-12 form-group input-space clearfix">';
                    dataHtml += '<input type="hidden" name="type" value="modify"><input type="hidden" name="uuid" value="'+arrdate[i].uuid+'">';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">名称：</label><input type="text" class="form-control" name="parkareaname" value="'+arrdate[i].name+'" ></div>';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1" title="同一充电站唯一">编号：</label><input type="number" name="parkareacode" class="form-control" value="'+arrdate[i].code+'" readonly></div>';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 " style="margin:auto;"><a href="javascript:park_space_details(\''+arrdate[i].uuid+'\');" style="line-height: 34px;">查看停车位</a></div></div>';
                    dataHtml += '<div class="col-md-12 form-group input-space clearfix">';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">开放时间：</label><input type="text" name="parkareaopenat" class="form-control" value="'+ arrdate[i].openat +'"></div>';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">结束时间：</label><input type="text" name="parkareacloseat" class="form-control" value="'+ arrdate[i].closeat +'"></div>';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">是否默认：</label><input type="radio" name="defaultshow" '+(arrdate[i].defaultshow==1?'checked':'')+' value="#'+arrdate[i].uuid+'"></div>';
                    dataHtml += '</div>';
                    dataHtml += '<div class="col-md-12 form-group input-space clearfix">';
                    dataHtml += '<div class="col-md-6 col-sm-6 col-xs-6"><label class="label-width1" style="vertical-align: top;margin-top: 5px;">收费标准：</label><textarea class="form-control" name="parkingfee" style="height: 100px;" >'+arrdate[i].parkingfee+'</textarea></div>';
                    dataHtml += '<div class="col-md-6 col-sm-6 col-xs-6"><label class="label-width1" style="vertical-align: top;margin-top: 5px;">相关描述：</label><textarea class="form-control" name="parkingdesc" style="height: 100px;" >'+arrdate[i].parkingdesc+'</textarea></div>';
                    dataHtml += '</div></div>';
                    nthTabs.addTab({
                        id:arrdate[i].uuid,
                        title:arrdate[i].name,
                        content:dataHtml,
                        allowClose:false
                    });
                    if(i == 0){
                        nthTabs.setActTab(arrdate[i].uuid);
                    }
                }

            };
        },
        error:function(data){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}
//保存
function saveStation(){
    var data = {};
    data.station = {};
    data.station.stationname = $("#name").val();// 充电站名

    data.station.address = $("#detailAddress").val(); // 详细地址
    data.station.lat = $("#lat").val(); // 经度
    data.station.lng = $("#lng").val(); // 纬度
    data.station.altitude = $("#altitude").val();
    data.station.managerorgCode = $("#managerorgCode").attr('data-id'); // 运维单位
    data.station.prorgcode = $("#prorgCode").attr('data-id'); // 运维单位
    data.station.servicephone = $("#serverPhone").val(); // 服务电话
    data.station.isthird = $("#isThirdInfo").val(); // 是否第三方
    data.station.operatoruuid = $("#operatorUuid").val(); //运营商
    data.station.stationtype = $("#stationType").val().split("-")[1]; // 站点类型
    data.station.urposetype = $("#useFun").val().split("-")[0];// 公专用
    data.station.servicecode = $("#useFun").val().split("-")[1];// 内部外部
    data.station.construction = $("#buildArea").val(); // 建设场所
    data.station.uuid = $("#uuid").val();
    data.station.gscode = $("#gsname").val();
    data.station.gsname = $("#gsname").text();
    //行政区划
    var distr = $("#cityCompany").attr("data-id");
    if(distr && distr.split("-").length == 3){
        data.station.provincecode=distr.split("-")[0];
        data.station.citycode=distr.split("-")[1];
        data.station.districtcode=distr.split("-")[2];
    }

    var orgcodes = $("#orgCode").attr('data-pids');
    debugger;
    console.log(orgcodes);
    if(orgcodes){
        if(orgcodes.split("-").length == 3){
            data.station.partorgcode = orgcodes.split("-")[2];
            data.station.cityorgcode = orgcodes.split("-")[1];
            data.station.provinceorgcode = orgcodes.split("-")[0];
        } else if (orgcodes.split("-").length == 2){
            data.station.partorgcode = '';
            data.station.cityorgcode = orgcodes.split("-")[1];
            data.station.provinceorgcode = orgcodes.split("-")[0];
        } else if (orgcodes.split("-").length == 1){
            data.station.partorgcode = '';
            data.station.cityorgcode = '';
            data.station.provinceorgcode = orgcodes.split("-")[0];
        }

    }


    if($("#standard").val()){
        data.station.standard = $("#standard").val().toString();
    }
    data.station.gsname = $("#gsname").val();

    data.station.tradetypes="";
    var groupCheckbox=$("input[name='tradeTypes']");
    for(var i=0;i<groupCheckbox.length;i++){
        if(groupCheckbox[i].checked){
            data.station.tradetypes+=groupCheckbox[i].value+",";
        }
    }

    data.parkingAreaList = [];
    var tablist = nthTabs.getTabList();
    for (var i = 0;i<tablist.length;i++){
        var parkingarea = {};
        var type = $(tablist[i].id+" input[name='type']").val();
        var urls = '';
        if(type == 'add'){
            urls = '/base/stations/insert';
            parkingarea.uuid='';
        } else {
            urls = '/base/stations/update';
            parkingarea.uuid=$(tablist[i].id+" input[name='uuid']").val();
        }
        parkingarea.name = $(tablist[i].id+" input[name='parkareaname']").val();
        parkingarea.openat= $(tablist[i].id+" input[name='parkareaopenat']").val();
        parkingarea.closeat= $(tablist[i].id+" input[name='parkareacloseat']").val();
        parkingarea.parkingfee= $(tablist[i].id+" textarea[name='parkingfee']").val();
        parkingarea.parkingdesc= $(tablist[i].id+" textarea[name='parkingdesc']").val();
        if($("input[name='defaultshow']:checked").val() == tablist[i].id){
            parkingarea.defaultshow = 1;
        } else {
            parkingarea.defaultshow = 0;
        }
        data.parkingAreaList.push(parkingarea);
    }
    $.ajax({
        url:projectPath + urls,
        type:'POST',
        data:JSON.stringify(data),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if(data.code != 0){
                layerAlert.errorMessage("操作失败");
            } else {
                layerAlert.successMessage2("操作成功");
            }
            $('#tb_ads').bootstrapTable('refresh');
        },
        error:function(data){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}

function validatorStation(){
    var bootstrapValidator = $('#stationForm').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
          /*  valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'*/
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '充电站是必填项'
                    }
                }
            },
            orgCode: {
                validators: {
                    notEmpty: {
                        message: 'The orgCode is required'
                    }
                }
            },
            managerorgCode: {
                validators: {
                    notEmpty: {
                        message: 'The managerorgCode is required'
                    }
                }
            },lat: {
                validators: {
                    notEmpty: {
                        message: 'The managerorgCode is required'
                    }
                }
            },lng: {
                validators: {
                    notEmpty: {
                        message: 'The managerorgCode is required'
                    }
                }
            },
        }
    });
    return bootstrapValidator.data('bootstrapValidator');
}
// 停车区对应的停车位列表展示
function park_space_details(uuid){
    var index = layer.open({
        type:1,
        title:"停车位详情",
        shade:0.3,
        shadeClose: true,
        move :false,
        area: ['80%', '60%'],
        skin: 'layui-layer-rims',
        content:$(".tab_parking_space"),
        btn:['关闭'],
        fixed:false,
        resize:true,
        // maxmin:true,
        success:function(){
            if(uuid!=''){
                $('#tab_parking_space').bootstrapTable('refresh', {url: projectPath+"/base/parking/spaces/listByArea",query:{areauuid:uuid}});
            } else {

            }
        },
        btn1:function(){
            layer.close(index);
        }
    })
};

function stakeQueryParams(){
    return {stationuuid:$("#uuid").val()};
}

function queryParkingParams(){
    return {};
}

/**
 * zhangYiHang 18.3.20
 * 页面按钮控制
 * @constructor
 */
function buttenControl() {
    var urls = paramUrlByButten();
    if(urls.length>0){
        for (var i in urls){
            if('update' == urls[i]){
                $("#btnRevise").show();
            } else if('insert' == urls[i]){
                $("#btnAdd").show();
            }else if('delete' == urls[i]){
                $("#btnDelete").show()
            }else if('excel' == urls[i]){
                $("#btnExport").show()
            }
        }
    }
}
